﻿using System;

namespace csharpcore7_ch3_flags_enum
{
    class FlagsEnumExample1
    {
        static void _Main()
        {
            BorderSides leftRight = BorderSides.Left | BorderSides.Right;
            Console.WriteLine((int)leftRight); //3
            if ((leftRight & BorderSides.Left) != 0)
                Console.WriteLine("Includes Left"); //Include Left
            string formatted = leftRight.ToString(); //"Left,Right"
            Console.WriteLine(formatted);
            BorderSides s = BorderSides.Left;
            s |= BorderSides.Right;
            Console.WriteLine(s == leftRight);      //True

            s ^= BorderSides.Right;  // Toggles BorderSides.Right
            Console.WriteLine(s);   //Left

            //枚举的真实值超过枚举类型成员的数值范围
            BorderSides b = (BorderSides)12345;
            Console.WriteLine(b);//12345

            BorderSides b1 = BorderSides.Bottom;
            b1++; //No errrs

            //Enum.IsDefined,只对标志枚举类型不起作用
            Console.WriteLine(Enum.IsDefined(typeof(BorderSides),b)); //false

            for (int i = 0; i <= 16; i++)
            {
                BorderSides side = (BorderSides)i;
                Console.WriteLine(IsFlagDefined(side) + " " + side);
            }


            for (int i = 0; i <= 16; i++)
            {
                EnumColor color = (EnumColor)i;
                Console.WriteLine(IsFlagDefined(color) + " " + color);
            }
        }
        /// <summary>
        /// 对标志枚举类型成员是否超出数据范围
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        static bool IsFlagDefined(Enum e)
        {
            decimal d;
            return !decimal.TryParse(e.ToString(), out d);
        }
    }

    [Flags]
    public enum BorderSides { None=0,Left=1,Right=2,Top=4,Bottom=8 }

    //合并的成员直接放在枚举的声明内
    [Flags]
    public enum BorderSide1
    { 
        None = 0, 
        Left = 1, Right = 2, Top = 4, Bottom = 8,
        LeftRight = Left | Right,
        TopBottom = Top | Bottom,
        All       = LeftRight | TopBottom
    }

    public enum EnumColor { Green = 1, Red = 2, Black = 3, White = 4}
}
